package com.guaji.system.NoteAPP.adapter

import android.net.Uri
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.guaji.system.NoteAPP.NoteMainActivity
import com.guaji.system.NoteAPP.data.Note
import com.bumptech.glide.Glide
import com.guaji.system.R
import java.io.File
import java.text.SimpleDateFormat
import java.util.*

class NoteAdapter(
    private val notes: MutableList<Note>, // 使用可变列表
    private val onNoteClick: (Note) -> Unit
) : RecyclerView.Adapter<NoteAdapter.NoteViewHolder>() {

    inner class NoteViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        val titleTextView: TextView = itemView.findViewById(R.id.note_title)
        val contentTextView: TextView = itemView.findViewById(R.id.note_content)
        val timestampTextView: TextView = itemView.findViewById(R.id.note_timestamp)
        val imageView: ImageView = itemView.findViewById(R.id.note_image)
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): NoteViewHolder {
        val view = LayoutInflater.from(parent.context)
            .inflate(R.layout.notelist, parent, false)
        return NoteViewHolder(view)
    }

    override fun onBindViewHolder(holder: NoteViewHolder, position: Int) {
        val note = notes[position]
        holder.titleTextView.text = note.title
        holder.contentTextView.text = note.content

        // 格式化时间戳（例如：2023-10-01 15:30:20）
        val dateFormat = SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault())
        holder.timestampTextView.text = dateFormat.format(Date(note.timestamp))

        // 加载图片（如果有）
        if (note.imageUri?.isNotEmpty() == true) {
            holder.imageView.visibility = View.VISIBLE
            Glide.with(holder.itemView.context)
                .load(Uri.fromFile(File(note.imageUri))) // 从本地路径加载
                .centerCrop()
                .placeholder(R.drawable.add) // 占位图（需自行添加）
                .error(R.drawable.add) // 错误图（需自行添加）
                .into(holder.imageView)
        } else {
            holder.imageView.visibility = View.GONE // 无图片时隐藏
        }

        // 笔记项点击事件
        holder.itemView.setOnClickListener {
            onNoteClick(note)
        }
    }

    override fun getItemCount(): Int = notes.size

    // 更新笔记列表
    fun updateNotes(newNotes: List<Note>) {
        notes.clear()
        notes.addAll(newNotes)
        notifyDataSetChanged()
    }

    // 提供一个公共方法来获取 notes
    fun getNotes(): List<Note> {
        return notes
    }
}
